package br.com.seuimovelnamao.interceptor;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Session;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import br.com.seuimovelnamao.controller.ImovelController;
import br.com.seuimovelnamao.model.Imovel;
import br.com.seuimovelnamao.model.Usuario;

public class GetImoveisInterceptor extends HandlerInterceptorAdapter {
	
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		
		String uri = request.getRequestURI();
		
		// Se esta na area de membros, carrega os imoveis na sessao
		if(uri.contains("memberArea")){
			if(request.getSession().getAttribute("usuario") != null){
				if(request.getSession().getAttribute("imoveis") != null)
					request.getSession().removeAttribute("imoveis");
				// carrega os imoveis do usuario na sessao
				Usuario usuario = (Usuario)request.getSession().getAttribute("usuario");
				Session session = (Session)request.getAttribute("hibernateSession");
				
				List<Imovel> imoveis = new ImovelController().getImoveisPorUsuario(usuario, session);
				request.getSession().setAttribute("imoveis", imoveis);
			}
		}

		return true;
		
	}

}
